#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :page_2.py
# @Time      :2024/10/14 18:27
# @Author    :zhou_yi
import streamlit as st
from st_componets.my_st_comps import st_select_box_dic_opt
from st_componets.st_form import st_three_price_form
from st_componets.st_fn import Fn
from st_componets.st_init import st_session_init

st_session_init()  # 会话设置
# st.set_page_config(page_title='功能管理', layout='wide')
"""  ----------------------页面-page2---------------------------   """

st.markdown('### 三方比价')
st.divider()

all_companies: list = Fn.get_company("三方比价")  # 从数据库中获得所有三方比价公司

# 侧边栏
with st.sidebar:
    with st.container(border=True):
        st.subheader("参数配置")

        # 从数据库拿甲方名称列表
        partA_list = Fn.get_company('有害垃圾', '清运')

        if not partA_list:
            st.error('数据库故障...待维护')
            st.stop()

        partA = st.selectbox(label='甲方', options=[itm['name'] for itm in partA_list] + ['新增'])
        st.session_state.partA = partA

        if partA == '新增':
            new_partA = st.text_input(label='xxx', placeholder='输入甲方公司名称', label_visibility='hidden')
            st.session_state.partA = new_partA

        Fn.start_date_to_end_date()  # 时间范围选择器

        current_tpl = st_select_box_dic_opt(label='应用模板', options=Fn.get_tpl_files(key="三方比价_模版"))
        st.session_state.current_tpl = current_tpl

        with st.form('sidebar_options', border=False, enter_to_submit=False):
            colB = st.columns([6, 2])
            with colB[0]:
                company_selects = st.multiselect(label='选择比价公司',
                                                 options=[itm['name'] for itm in all_companies],
                                                 placeholder='选择3家公司')

            with colB[1]:
                st.write('')
                st.write('')
                if st.form_submit_button('确认'):
                    st.session_state.three_price_company = company_selects

# 中心区域  表单 输入数据
if st.session_state.three_price_company:

    # 求长度，生成表单的数量
    _len = len(st.session_state.three_price_company)
    if _len != 3:
        st.warning('比价公司为3家')
        st.stop()

    # 根据列表的长度 生成st列对象
    _cols = st.columns(_len)

    _tmp = []  # 遍历列表 依据选择的公司名称缓存对应的字典
    for _company_name, _init_signal_price in zip(st.session_state.three_price_company,
                                                 st.session_state.init_signal_price):
        # 根据筛选的公司名，获得公司信息字典
        _default: dict = list(filter(lambda x: x['name'] == _company_name, all_companies))[0]
        _default['signal_price'] = _init_signal_price  # 初始化时候设置的单价
        _default['months'] = st.session_state.months
        _default['sign_date'] = Fn.get_sign_date()  # 签名日期
        _tmp.append(_default)

    # 缓存当前选择的三方比价公司数据（三家）
    st.session_state.three_price_form_catch = _tmp

    # 遍历缓存数据，生成表单，表单返回值更新缓存字典
    for _idx, _dic in enumerate(st.session_state.three_price_form_catch):
        with _cols[_idx]:
            st.markdown(f"##### No{_idx + 1}. 输入第{_idx + 1}家公司数据")
            _form_res: dict = st_three_price_form(key=f'form_{_idx}', default_value=_dic)  # 生成表单，并传入数据
        _dic.update(_form_res)  # 更新缓存数据

    # 模版需要的数据
    st.session_state.context = {
        'partA': st.session_state.partA,
        'service_date': Fn.service_date(),
        'months': f"{st.session_state.months}",
        'three': Fn.three_price_data_to_appear(data_lst=st.session_state.three_price_form_catch)
    }

    # 显示模版需要的数据
    with st.container(border=True, key='appear'):
        Fn.res_appear(appear_dic=st.session_state.context)

    # 下载
    with st.container(border=True, key='down'):
        with st.columns(3)[0]:
            Fn.download_three_price_docx_file(
                tpl=st.session_state.current_tpl,
                context=st.session_state.context
            )
